package net.srcz.jsjvm.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.srcz.jsjvm.core.Converter;

public class ClassTranslationServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		String path = req.getPathInfo();
		if(!path.startsWith("/classes/")) {
			if(path.equals("/"))
				path = "/test.html";
			File f = new File(path.substring(1));
			if(!f.exists()) {
				resp.sendError(404);
				return;
			}
			FileInputStream fis = new FileInputStream(f);
			while(true) {
				byte[] buff = new byte[512];
				int nb = fis.read(buff);
				if(nb < 0)
					break;
				resp.getOutputStream().write(buff,0,nb);
			}
			return;
		}
	//	resp.setContentType("script/javascript");
		path = path.substring("/classes/".length());
		String res = path.replace(".class.js",".class");
		System.out.println(res);
		InputStream is = getClass().getClassLoader().getResourceAsStream(res);
		if(is == null) {
			resp.sendError(404);
			return;
		}
		
		
		try {
			Converter.convert(is, resp.getOutputStream());
		} catch(Exception ex) {
			ex.printStackTrace();
		}
	}

}
